using System.Web.Security;
using System.Configuration.Provider;
using System.Collections.Specialized;
using System;
using System.Data;
using System.Data.Odbc;
using System.Configuration;
using System.Diagnostics;
using System.Web;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Web.Configuration;
using System.Collections.Generic;

using Microsoft.ConnectionEngine.Common.Security;
using Microsoft.ConnectionEngine.Registers.Core.ServiceProvider.Common;

namespace Microsoft.ConnectionEngine.Registers.Core.ServiceProvider.Business
{
    internal class HSDMembershipProvider : ProviderBase
    {
        #region Member Variables

        private string name;
        private string applicationName;
        private string description;
        private bool enablePasswordReset;
        private bool enablePasswordRetrieval;
        private int maxInvalidPasswordAttempts;
        private int minRequiredNonAlphanumericCharacters;
        private int minRequiredPasswordLength;
        private int passwordAttemptWindow;
        private MembershipPasswordFormat passwordFormat;
        private MembershipPasswordFormat membershipPasswordFormat;
        private string passwordStrengthRegularExpression;
        private bool requiresQuestionAndAnswer;
        private bool requiresUniqueEmail;

        #endregion

        #region Constructors

        /// <summary>
        /// Default constructor
        /// </summary>
        public HSDMembershipProvider()
        {
            // TODO: Add constructor logic here
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Initialises the membership provider
        /// </summary>
        /// <param name="name1">The name of the membership provider</param>
        /// <param name="config">A name/value collection of config values</param>
        /// sajoshi - Changed the name to name1 : 5/14/2007. ISSUE ID: 1434
        public override void Initialize(string name1, System.Collections.Specialized.NameValueCollection config)
        {
            // Verify that config isn't null
            //if (config == null) { throw new ArgumentNullException("NameValueCollection \"config\" is null."); }

            // Assign the provider a default name if it doesn't have one
            if (String.IsNullOrEmpty(name1)) { name1 = "HSDMembershipProvider"; }
            this.name = name1;

            // Initialise base class
            base.Initialize(this.name, config);

            applicationName = GetValueFromConfig(config, "applicationName", "MerlinRefApp");
            description = GetValueFromConfig(config, "dscription", "");
            enablePasswordReset = Convert.ToBoolean(GetValueFromConfig(config, "enablePasswordReset", "true"));
            enablePasswordRetrieval = Convert.ToBoolean(GetValueFromConfig(config, "enablePasswordRetrieval", "true"));
            maxInvalidPasswordAttempts = Convert.ToInt32(GetValueFromConfig(config, "maxInvalidPasswordAttempts", "5"));
            minRequiredNonAlphanumericCharacters = Convert.ToInt32(GetValueFromConfig(config, "minRequiredNonAlphanumericCharacters", "1"));
            minRequiredPasswordLength = Convert.ToInt32(GetValueFromConfig(config, "minRequiredPasswordLength", "7"));
            passwordAttemptWindow = Convert.ToInt32(GetValueFromConfig(config, "passwordAttemptWindow", "10"));
            passwordStrengthRegularExpression = Convert.ToString(GetValueFromConfig(config, "passwordStrengthRegularExpression", ""));
            requiresQuestionAndAnswer = Convert.ToBoolean(GetValueFromConfig(config, "requiresQuestionAndAnswer", "false"));
            requiresUniqueEmail = Convert.ToBoolean(GetValueFromConfig(config, "requiresUniqueEmail", "true"));

            // Load password format
            string passwordFormatName = GetValueFromConfig(config, "passwordFormat", "Hashed");
            switch (passwordFormatName)
            {
                case "Hashed":
                    passwordFormat = MembershipPasswordFormat.Hashed;
                    break;
                case "Encrypted":
                    passwordFormat = MembershipPasswordFormat.Encrypted;
                    break;
                case "Clear":
                    passwordFormat = MembershipPasswordFormat.Clear;
                    break;
                default:
                    throw new ProviderException("Password format not supported.");
            }
        }


        /// <summary>
        /// Validates a username and password as belonging to a valid membership user 
        /// </summary>
        /// <param name="userName">The username of the user to validate</param>
        /// <param name="password">The password to validate</param>
        /// <returns>True if the username and password are a correct match</returns>
        public bool ValidateUser(string userName, string password)
        {
            // Load membership user data
            AspnetMembershipUser aspnetMembershipUser = AspnetMembershipUserManager.GetByUserName(userName);
            if (aspnetMembershipUser != null)
            {
                // Validate password
                if (AspnetMembershipUserManager.ValidatePassword(aspnetMembershipUser, password, passwordFormat))
                {
                    // raise Validating password event
                    ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(userName, password, true);
                    //OnValidatingPassword(args);
                    if (args.Cancel)
                    {
                        throw args.FailureInformation;
                    }
                    return true;
                }
            }
            return false;
        }


        /// <summary>
        /// Changes the password of a membership user
        /// </summary>
        /// <param name="userName">The username of the user to update</param>
        /// <param name="oldPassword">The old password</param>
        /// <param name="newPassword">The new password</param>
        /// <returns>True if successful</returns>        
        public bool ChangePassword(string userName, string oldPassword, string newPassword)
        {
            // Load membership user
            AspnetMembershipUser aspnetMembershipUser = AspnetMembershipUserManager.GetByUserName(userName);
            if (aspnetMembershipUser != null)
            {
                return AspnetMembershipUserManager.ChangePassword(aspnetMembershipUser, oldPassword, newPassword, passwordFormat);
            }
            return false;
        }


        /// <summary>
        /// Gets a membership user by username
        /// </summary>
        /// <param name="userName">The user name of the user to get</param>
        /// <param name="userIsOnline">This parameter isn't used</param>
        /// <returns>The requested membership user</returns>
        public AspnetMembershipUser GetUser(string userName, bool userIsOnline)
        {
            // Load membership user data
            AspnetMembershipUser aspnetMembershipUser = AspnetMembershipUserManager.GetByUserName(userName);
            if (aspnetMembershipUser != null)
            {
                // Convert to system class and return
                //return ConvertAspnetMembershipUserToMembershipUser(aspnetMembershipUser);
                return aspnetMembershipUser;
            }
            return null;
        }


        /// <summary>
        /// Gets a membership user by ID
        /// </summary>
        /// <param name="providerUserKey">The membership user ID</param>
        /// <param name="userIsOnline">true to update the last-activity datetime for the user, otherwise false</param>
        /// <returns></returns>
        public AspnetMembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            // Load membership user data
            AspnetMembershipUser aspnetMembershipUser = AspnetMembershipUserManager.GetByUserID(new Guid(providerUserKey.ToString()));
            if (aspnetMembershipUser != null)
            {
                // Convert to system class and return
                //return ConvertAspnetMembershipUserToMembershipUser(aspnetMembershipUser);
                return aspnetMembershipUser;
            }
            return null;
        }


        /// <summary>
        /// Changes the password hint question/answer of a membership user
        /// </summary>
        /// <param name="userName">The username of the user to update</param>
        /// <param name="password">The password of the user to update</param>
        /// <param name="newPasswordQuestion">The new password hint question</param>
        /// <param name="newPasswordAnswer">The new password hint answer</param>
        /// <returns>True if successful</returns>
        public bool ChangePasswordQuestionAndAnswer(string userName, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            // Load membership user
            AspnetMembershipUser aspnetMembershipUser = AspnetMembershipUserManager.GetByUserName(userName);
            if (aspnetMembershipUser != null)
            {
                return AspnetMembershipUserManager.ChangePasswordQuestionAndAnswer(aspnetMembershipUser, password, newPasswordQuestion, newPasswordAnswer, passwordFormat);
            }
            return false;
        }


        /// <summary>
        /// Deletes a user by username
        /// </summary>
        /// <param name="userName">The username of the user to delete</param>
        /// <param name="deleteAllRelatedData">This parameter isn't used</param>
        /// <returns>True if successful</returns>
        public bool DeleteUser(string userName, bool deleteAllRelatedData)
        {
            // Load by username (to find userID)
            AspnetMembershipUser aspnetMembershipUser = AspnetMembershipUserManager.GetByUserName(userName);
            if (aspnetMembershipUser != null)
            {
                // Delete by userID
                AspnetMembershipUserManager.Delete(aspnetMembershipUser);
                return true;
            }
            return false;
        }


        /// <summary>
        /// Updates a membershp user in the database
        /// </summary>
        /// <param name="user">A system membership user representing the user to update</param>
        public void UpdateUser(AspnetMembershipUser user)
        {
            //AspnetMembershipUser aspnetMembershipUser = ConvertMembershipUserToAspnetMembershipUser(user);
            AspnetMembershipUserManager.Update(user);
        }


        /// <summary>
        /// Creates a new membership user in the database
        /// </summary>
        /// <param name="userName">The user name of the new user</param>
        /// <param name="password">The password of the new user</param>
        /// <param name="email">The email address of the new user</param>
        /// <param name="passwordQuestion">The password question of the new user</param>
        /// <param name="passwordAnswer">The password answer of the new user</param>
        /// <param name="isApproved">True if the new user is approved</param>
        /// <param name="providerUserKey">The new ID of the user membership</param>
        /// <param name="hcuId">The ID of the healthcare user </param>
        /// <param name="providerId">The ID of the service provider</param>
        /// <param name="status">Outbound parameter representing the status of the creation attempt</param>
        /// <returns>The newly created/inserted user (or null if the insert failed)</returns>
        public AspnetMembershipUser CreateUser(string userName, string password, string email, string passwordQuestion, 
            string passwordAnswer, bool isApproved, object providerUserKey, string hcuId, string providerId, out MembershipCreateStatus status)
        {
            string sUserNameByEmail = null;
            // raise Validating password event
            ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(userName, password, true);
            //OnValidatingPassword(args);
            if (args.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            // check for duplicate email address
            //Work Item ID: 1595
            //Modified By: SachinJo
            sUserNameByEmail = this.GetUserNameByEmail(email);
            if (this.RequiresUniqueEmail &&  !string.IsNullOrEmpty(sUserNameByEmail) )
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return null;
            }

            // check for duplicate user name
            if (AspnetMembershipUserManager.GetByUserName(userName) != null)
            {
                status = MembershipCreateStatus.DuplicateUserName;
                return null;
            }

            // generate new id if user key is null
            if (providerUserKey == null) { providerUserKey = Guid.NewGuid(); }

            AspnetMembershipUser aspnetMembershipUser = new AspnetMembershipUser();
            //TODO:
            //aspnetMembershipUser.ApplicationID = AspnetMembershipUserManager.GetApplicationID(this.applicationName);
            aspnetMembershipUser.ApplicationID = new Guid("{3866117F-A9DC-4257-BD08-A4A9DD73F372}");
            aspnetMembershipUser.UserID = new Guid(providerUserKey.ToString());
            aspnetMembershipUser.Comment = "";
            aspnetMembershipUser.CreateDate = DateTime.Now;
            aspnetMembershipUser.FailedPasswordAnswerAttemptCount = 0;
            aspnetMembershipUser.FailedPasswordAttemptCount = 0;
            aspnetMembershipUser.IsAnonymous = false;
            aspnetMembershipUser.IsApproved = isApproved;
            aspnetMembershipUser.HCUID = hcuId;
            aspnetMembershipUser.ProviderId = providerId;
            aspnetMembershipUser.IsLockedOut = false;
            aspnetMembershipUser.Email = email;
            aspnetMembershipUser.LoweredEmail = email.ToLower();
            aspnetMembershipUser.LoweredUserName = userName.ToLower();
            aspnetMembershipUser.MobileAlias = string.Empty;
            aspnetMembershipUser.MobilePIN = string.Empty;
            aspnetMembershipUser.PasswordAnswer = passwordAnswer;
            aspnetMembershipUser.PasswordFormat = (int)this.PasswordFormat;
            aspnetMembershipUser.PasswordQuestion = passwordQuestion;
            aspnetMembershipUser.UserName = userName;
            aspnetMembershipUser.Password = password;

            AspnetMembershipUserManager.Insert(aspnetMembershipUser);
            status = MembershipCreateStatus.Success;

            //return ConvertAspnetMembershipUserToMembershipUser(aspnetMembershipUser);
            return aspnetMembershipUser;

        }


        /// <summary>
        /// Creates a new membership user in the database
        /// </summary>
        /// <param name="userName">The user name of the new user</param>
        /// <param name="password">The password of the new user</param>
        /// <param name="email">The email address of the new user</param>
        /// <param name="passwordQuestion">The password question of the new user</param>
        /// <param name="passwordAnswer">The password answer of the new user</param>
        /// <param name="isApproved">True if the new user is approved</param>
        /// <param name="providerUserKey">The new ID of the user membership</param>        
        /// <param name="status">Outbound parameter representing the status of the creation attempt</param>
        /// <returns>The newly created/inserted user (or null if the insert failed)</returns>
        public AspnetMembershipUser CreateUser(string userName, string password, string email, string passwordQuestion,
            string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            string sUserNameByEmail = null;

            // raise Validating password event
            ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(userName, password, true);
            //OnValidatingPassword(args);
            if (args.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            //Work Item ID: 1594
            //Modified By: SachinJo
            // check for duplicate email address
            sUserNameByEmail = this.GetUserNameByEmail(email);
            if (this.RequiresUniqueEmail &&  !string.IsNullOrEmpty(sUserNameByEmail))
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return null;
            }

            // check for duplicate user name
            if (AspnetMembershipUserManager.GetByUserName(userName) != null)
            {
                status = MembershipCreateStatus.DuplicateUserName;
                return null;
            }

            // generate new id if user key is null
            if (providerUserKey == null) { providerUserKey = Guid.NewGuid(); }

            AspnetMembershipUser aspnetMembershipUser = new AspnetMembershipUser();

            aspnetMembershipUser.ApplicationID = AspnetMembershipUserManager.GetApplicationID(this.applicationName);
            aspnetMembershipUser.UserID = new Guid(providerUserKey.ToString());
            aspnetMembershipUser.Comment = "";
            aspnetMembershipUser.CreateDate = DateTime.Now;
            aspnetMembershipUser.FailedPasswordAnswerAttemptCount = 0;
            aspnetMembershipUser.FailedPasswordAttemptCount = 0;
            aspnetMembershipUser.IsAnonymous = false;
            aspnetMembershipUser.IsApproved = isApproved;            
            aspnetMembershipUser.IsLockedOut = false;
            aspnetMembershipUser.Email = email;
            aspnetMembershipUser.LoweredEmail = email.ToLower();
            aspnetMembershipUser.LoweredUserName = userName.ToLower();
            aspnetMembershipUser.MobileAlias = string.Empty;
            aspnetMembershipUser.MobilePIN = string.Empty;
            aspnetMembershipUser.PasswordAnswer = passwordAnswer;
            aspnetMembershipUser.PasswordFormat = (int)this.PasswordFormat;
            aspnetMembershipUser.PasswordQuestion = passwordQuestion;
            aspnetMembershipUser.UserName = userName;
            aspnetMembershipUser.Password = password;

            AspnetMembershipUserManager.Insert(aspnetMembershipUser);
            status = MembershipCreateStatus.Success;

            //return ConvertAspnetMembershipUserToMembershipUser(aspnetMembershipUser);
            return aspnetMembershipUser;

        }

        /// <summary>
        /// Returns the password of a user (if the answer to the password question is correct)
        /// </summary>
        /// <param name="userName">The username of the membership user to return the password of</param>
        /// <param name="answer">The answer to the user's password question</param>
        /// <returns>
        /// If the answer is correct, will return either the user's current password (if the password 
        /// format is encrypted or clear) or sets/returns a new password (if the password format is hashed)
        /// </returns>
        public string GetPassword(string userName, string answer)
        {
            // validate password retrieval is enabled
            if (!this.EnablePasswordRetrieval) { throw new ProviderException("Password Retrieval Not Enabled."); }

            // can't return hashed passwords
            if (this.PasswordFormat == MembershipPasswordFormat.Hashed) { throw new ProviderException("Cannot retrieve Hashed passwords."); }

            // Load membership user data
            AspnetMembershipUser aspnetMembershipUser = AspnetMembershipUserManager.GetByUserName(userName);
            if (aspnetMembershipUser != null)
            {
                // is question/answer is not required, set answer to answer in database
                if (!this.RequiresQuestionAndAnswer) answer = aspnetMembershipUser.PasswordAnswer;
                return AspnetMembershipUserManager.GetPasswordByQuestionAnswer(aspnetMembershipUser, answer, passwordFormat);
            }
            return string.Empty;
        }


        /// <summary>
        /// Returns the password of a user (if the answer to the password question is correct)
        /// </summary>
        /// <param name="userName">The username of the membership user to return the password of</param>
        /// <param name="answer">The answer to the user's password question</param>
        /// <returns>
        /// If the answer is correct, will return either the user's current password (if the password 
        /// format is encrypted or clear) or sets/returns a new password (if the password format is hashed)
        /// </returns>
        public string ResetPassword(string userName, string answer)
        {
            // validate password reset is enabled
            if (!this.EnablePasswordReset) { throw new NotSupportedException("Password reset is not enabled."); }

            // validate answer has been provided if required
            if (answer == null && this.RequiresQuestionAndAnswer) { throw new ProviderException("Password answer required for password reset."); }

            // Load membership user data
            AspnetMembershipUser aspnetMembershipUser = AspnetMembershipUserManager.GetByUserName(userName);
            if (aspnetMembershipUser != null)
            {
                // is question not required, set answer to one in the database
                if (!this.RequiresQuestionAndAnswer) { answer = aspnetMembershipUser.PasswordAnswer; }

                string newPassword = AspnetMembershipUserManager.ResetPassword(aspnetMembershipUser, passwordFormat);

                // raise Validating password event
                ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(userName, newPassword, true);
                //OnValidatingPassword(args);
                if (args.Cancel) { throw args.FailureInformation; }

                return newPassword;
            }
            return string.Empty;
        }


        /// <summary>
        /// Returns the username of a membership user by email address
        /// </summary>
        /// <param name="email">The email address of the membership user to find</param>
        /// <returns>The username if a usermember is found, otherwise an empty string</returns>        
        public string GetUserNameByEmail(string email)
        {
            // Load membership user data
            AspnetMembershipUser aspnetMembershipUser = AspnetMembershipUserManager.GetByEmail(email);
            if (aspnetMembershipUser != null)
            {
                return aspnetMembershipUser.UserName;
            }
            return string.Empty;
        }


        /// <summary>
        /// Gets all MembershipUsers from the database
        /// </summary>
        /// <param name="pageIndex">This parameter is ignored</param>
        /// <param name="pageSize">This parameter is ignored</param>
        /// <param name="totalRecords">The total number of users found</param>
        /// <returns>A collection of all membership users</returns>
        public MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection membershipUserCollection = new MembershipUserCollection();
            List<AspnetMembershipUser> aspnetMembershipUserList = AspnetMembershipUserManager.GetAll();

            // Loop through collection, convert each to system membership user, and add to collection
            int counter = 0;
            int startIndex = pageSize * pageIndex;
            int endIndex = startIndex + pageSize - 1;
            foreach (AspnetMembershipUser aspnetMembershipUser in aspnetMembershipUserList)
            {
                if (counter >= startIndex)
                {
                    membershipUserCollection.Add(ConvertAspnetMembershipUserToMembershipUser(aspnetMembershipUser));
                }

                if (counter >= endIndex) { break; }
                counter++;
            }
            totalRecords = aspnetMembershipUserList.Count;

            return membershipUserCollection;
        }


        /// <summary>
        /// Finds MembershipUsers from the database by email
        /// </summary>
        /// <param name="emailToMatch">The email address (or part of one) to find</param>
        /// <param name="pageIndex">This parameter is ignored</param>
        /// <param name="pageSize">This parameter is ignored</param>
        /// <param name="totalRecords">The total number of users found</param>
        /// <returns>A collection of all membership users</returns>
        public MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection membershipUserCollection = new MembershipUserCollection();
            List<AspnetMembershipUser> aspnetMembershipUserList = AspnetMembershipUserManager.FindByEmail(emailToMatch);

            // Loop through collection, convert each to system membership user, and add to collection
            int counter = 0;
            int startIndex = pageSize * pageIndex;
            int endIndex = startIndex + pageSize - 1;
            foreach (AspnetMembershipUser aspnetMembershipUser in aspnetMembershipUserList)
            {
                if (counter >= startIndex)
                {
                    membershipUserCollection.Add(ConvertAspnetMembershipUserToMembershipUser(aspnetMembershipUser));
                }

                if (counter >= endIndex) { break; }
                counter++;
            }
            totalRecords = aspnetMembershipUserList.Count;

            return membershipUserCollection;
        }


        /// <summary>
        /// Finds MembershipUsers from the database by user name
        /// </summary>
        /// <param name="usernameToMatch">The user name (or part of one) to find</param>
        /// <param name="pageIndex">This parameter is ignored</param>
        /// <param name="pageSize">This parameter is ignored</param>
        /// <param name="totalRecords">The total number of users found</param>
        /// <returns>A collection of all membership users</returns>
        public MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            MembershipUserCollection membershipUserCollection = new MembershipUserCollection();
            List<AspnetMembershipUser> aspnetMembershipUserList = AspnetMembershipUserManager.FindByUserName(usernameToMatch);

            // Loop through collection, convert each to system membership user, and add to collection
            int counter = 0;
            int startIndex = pageSize * pageIndex;
            int endIndex = startIndex + pageSize - 1;
            foreach (AspnetMembershipUser aspnetMembershipUser in aspnetMembershipUserList)
            {
                if (counter >= startIndex)
                {
                    membershipUserCollection.Add(ConvertAspnetMembershipUserToMembershipUser(aspnetMembershipUser));
                }

                if (counter >= endIndex) { break; }
                counter++;
            }
            totalRecords = aspnetMembershipUserList.Count;

            return membershipUserCollection;
        }

        /// <summary>
        /// Encrypts a password based on the selected password format
        /// </summary>
        /// <param name="password">The password to encrypt</param>
        /// <returns>The encrypted password</returns>
        protected byte[] EncryptPassword(byte[] password)
        {
            // return encrypted password (if password format is hashed/encrypted, otherwise returns plain text)
            return Convert.FromBase64String(AspnetMembershipUserManager.EncodePassword(Convert.ToBase64String(password), this.PasswordFormat));
        }


        /// <summary>
        /// Decrypts a password based on the selected password format
        /// </summary>
        /// <param name="password">The password to descrypt</param>
        /// <returns>The decrpyted password</returns>
        protected byte[] DecryptPassword(byte[] password)
        {
            // return decrypted password (if password format is encrypted, otherwise returns plain text)
            return Convert.FromBase64String(AspnetMembershipUserManager.DecodePassword(Convert.ToBase64String(password), this.PasswordFormat));
        }



        #endregion

        #region Private Methods

        /// <summary>
        /// Converts an aspnetMembershipUser object to a system MembershipUser
        /// </summary>
        /// <param name="aspnetMembershipUser">The aspnetMembershipUser object to convert</param>
        /// <returns>A system MembershipUser object based on the aspnetMembershipUser object</returns>
        internal MembershipUser ConvertAspnetMembershipUserToMembershipUser(AspnetMembershipUser aspnetMembershipUser)
        {
            return new MembershipUser(this.Name, aspnetMembershipUser.UserName, aspnetMembershipUser.UserID, aspnetMembershipUser.Email, 
                aspnetMembershipUser.PasswordQuestion, aspnetMembershipUser.Comment, aspnetMembershipUser.IsApproved, 
                aspnetMembershipUser.IsLockedOut, aspnetMembershipUser.CreateDate, aspnetMembershipUser.LastLoginDate, 
                aspnetMembershipUser.LastLoginDate, aspnetMembershipUser.LastPasswordChangedDate, aspnetMembershipUser.LastLockoutDate);
        }


        /// <summary>
        /// Converts a system MembershipUser to an aspnetMembershipUser object 
        /// </summary>
        /// <param name="membershipUser">The system MembershipUser to convert</param>
        /// <returns>A converted AspnetMembershipUser object</returns>
        internal AspnetMembershipUser ConvertMembershipUserToAspnetMembershipUser(MembershipUser membershipUser)
        {
            AspnetMembershipUser aspnetMembershipUser = AspnetMembershipUserManager.GetByUserName(membershipUser.UserName);
            if (aspnetMembershipUser != null)
            {
                aspnetMembershipUser.IsApproved = membershipUser.IsApproved;
                aspnetMembershipUser.IsLockedOut = membershipUser.IsLockedOut;
                aspnetMembershipUser.LastLoginDate = membershipUser.LastLoginDate;
                aspnetMembershipUser.LastPasswordChangedDate = membershipUser.LastPasswordChangedDate;
                aspnetMembershipUser.PasswordQuestion = membershipUser.PasswordQuestion;
                aspnetMembershipUser.Comment = membershipUser.Comment;
                aspnetMembershipUser.CreateDate = membershipUser.CreationDate;
                aspnetMembershipUser.Email = membershipUser.Email;
            }
            return aspnetMembershipUser;
        }


        /// <summary>
        /// Returns a value from a name/value collection by key
        /// </summary>
        /// <param name="config">The name/value collection</param>
        /// <param name="key">The name of the key to retrive the value of</param>
        /// <param name="defaultValue">The value to return if the key/value can't be found</param>
        /// <returns>Either the value matching the key, or the default value if the key can't be found</returns>
        internal string GetValueFromConfig(System.Collections.Specialized.NameValueCollection config, string key, string defaultValue)
        {
            try
            {
                return String.IsNullOrEmpty(config[key]) ? defaultValue : config[key];
            }
            catch(Exception ex)
            {
                //Use the Ex for Instrumentation in future. Issue is 1433.
                return defaultValue;
            }
        }

        #endregion

        #region Un-implemented methods

        public bool UnlockUser(string userName)
        {
            //Work Item ID: 1272
            //Modified By: SachinJo
            //throw new Exception("The method or operation is not implemented.");
            throw new NotImplementedException("The method or operation is not implemented.");
        }

        public int GetNumberOfUsersOnline()
        {
            //Work Item ID: 1272
            //Modified By: SachinJo
            //throw new Exception("The method or operation is not implemented.");
            throw new NotImplementedException("The method or operation is not implemented.");
        }

        #endregion

        #region Properties

        public string ApplicationName
        {
            get { return applicationName; }
            set { applicationName = value; }
        }
        //WorkItem 68 : Changed by sajoshi (23/Apr/2007)
        public new string Description
        {
            get { return description; }
        }

        public bool EnablePasswordReset
        {
            get { return enablePasswordReset; }
        }

        public bool EnablePasswordRetrieval
        {
            get { return enablePasswordRetrieval; }
        }

        public int MaxInvalidPasswordAttempts
        {
            get { return maxInvalidPasswordAttempts; }
        }

        public int MinRequiredNonAlphanumericCharacters
        {
            get { return minRequiredNonAlphanumericCharacters; }
        }

        public int MinRequiredPasswordLength
        {
            get { return minRequiredPasswordLength; }
        }

        public int PasswordAttemptWindow
        {
            get { return passwordAttemptWindow; }
        }

        public MembershipPasswordFormat PasswordFormat
        {
            get { return passwordFormat; }
        }

        public MembershipPasswordFormat MembershipPasswordFormat
        {
            get { return membershipPasswordFormat; }
            set { membershipPasswordFormat = value; }
        }

        public string PasswordStrengthRegularExpression
        {
            get { return passwordStrengthRegularExpression; }
        }

        public bool RequiresQuestionAndAnswer
        {
            get { return requiresQuestionAndAnswer; }
        }

        public bool RequiresUniqueEmail
        {
            get { return requiresUniqueEmail; }

        }

        public override string Name
        {
            get { return name; }
        }

        #endregion
    }
 }
